// 管理员界面专用JavaScript

// 管理员API客户端
class AdminApiClient extends ApiClient {
    // 检查管理员权限
    static async checkAdminPermission() {
        try {
            const response = await this.get('/api/admin/check');
            return response.success;
        } catch (error) {
            console.error('权限检查失败:', error);
            return false;
        }
    }
    
    // 获取统计数据
    static async getStatistics() {
        return await this.get('/api/admin/statistics');
    }
    
    // 用户管理API
    static async getUsers(params = {}) {
        return await this.get('/api/admin/users', params);
    }
    
    static async createUser(userData) {
        return await this.post('/api/admin/users', userData);
    }
    
    static async updateUser(userId, userData) {
        return await this.put(`/api/admin/users/${userId}`, userData);
    }
    
    static async deleteUser(userId) {
        return await this.delete(`/api/admin/users/${userId}`);
    }
    
    static async toggleUserStatus(userId) {
        return await this.post(`/api/admin/users/${userId}/toggle-status`);
    }
    
    static async resetUserPassword(userId) {
        return await this.post(`/api/admin/users/${userId}/reset-password`);
    }
    
    // 商品管理API
    static async getProducts(params = {}) {
        return await this.get('/api/admin/products', params);
    }
    
    static async createProduct(productData) {
        return await this.post('/api/admin/products', productData);
    }
    
    static async updateProduct(productId, productData) {
        return await this.put(`/api/admin/products/${productId}`, productData);
    }
    
    static async deleteProduct(productId) {
        return await this.delete(`/api/admin/products/${productId}`);
    }
    
    static async toggleProductStatus(productId) {
        return await this.post(`/api/admin/products/${productId}/toggle-status`);
    }
    
    // 评论管理API
    static async getReviews(params = {}) {
        return await this.get('/api/admin/reviews', params);
    }
    
    static async auditReview(reviewId, status, reason = '') {
        return await this.post(`/api/admin/reviews/${reviewId}/audit`, { status, reason });
    }
    
    static async deleteReview(reviewId) {
        return await this.delete(`/api/admin/reviews/${reviewId}`);
    }
    
    // 批量操作API
    static async batchDeleteUsers(userIds) {
        return await this.post('/api/admin/users/batch-delete', { userIds });
    }
    
    static async batchDeleteProducts(productIds) {
        return await this.post('/api/admin/products/batch-delete', { productIds });
    }
    
    static async batchAuditReviews(reviewIds, status, reason = '') {
        return await this.post('/api/admin/reviews/batch-audit', { reviewIds, status, reason });
    }
    
    static async batchDeleteReviews(reviewIds) {
        return await this.post('/api/admin/reviews/batch-delete', { reviewIds });
    }
    
    // 图表数据API
    static async getUserRegistrationTrend(days = 30) {
        return await this.get('/api/admin/charts/user-registration', { days });
    }
    
    static async getReviewDistribution() {
        return await this.get('/api/admin/charts/review-distribution');
    }
    
    static async getProductCategoryStats() {
        return await this.get('/api/admin/charts/product-category');
    }
    
    static async getMonthlyReviewTrend(months = 12) {
        return await this.get('/api/admin/charts/monthly-review', { months });
    }
    
    // 最近活动API
    static async getRecentUsers(limit = 10) {
        return await this.get('/api/admin/recent/users', { limit });
    }
    
    static async getRecentReviews(limit = 10) {
        return await this.get('/api/admin/recent/reviews', { limit });
    }
}

// 管理员界面工具类
class AdminUtils {
    // 初始化侧边栏
    static initSidebar() {
        const sidebarToggle = document.querySelector('.sidebar-toggle');
        const sidebar = document.querySelector('.admin-sidebar');
        const overlay = document.querySelector('.sidebar-overlay');
        
        if (sidebarToggle && sidebar) {
            sidebarToggle.addEventListener('click', () => {
                sidebar.classList.toggle('show');
                if (overlay) {
                    overlay.classList.toggle('show');
                }
            });
        }
        
        if (overlay) {
            overlay.addEventListener('click', () => {
                sidebar.classList.remove('show');
                overlay.classList.remove('show');
            });
        }
        
        // 设置当前页面的导航项为激活状态
        const currentPath = window.location.pathname;
        const navLinks = document.querySelectorAll('.admin-sidebar .nav-link');
        navLinks.forEach(link => {
            if (link.getAttribute('href') === currentPath) {
                link.classList.add('active');
            }
        });
    }
    
    // 初始化数据表格
    static initDataTable(tableId, options = {}) {
        const table = document.getElementById(tableId);
        if (!table) return;
        
        // 添加排序功能
        const headers = table.querySelectorAll('thead th[data-sort]');
        headers.forEach(header => {
            header.style.cursor = 'pointer';
            header.addEventListener('click', () => {
                const sortField = header.dataset.sort;
                const currentOrder = header.dataset.order || 'asc';
                const newOrder = currentOrder === 'asc' ? 'desc' : 'asc';
                
                // 清除其他列的排序标识
                headers.forEach(h => {
                    h.classList.remove('sort-asc', 'sort-desc');
                    h.dataset.order = '';
                });
                
                // 设置当前列的排序标识
                header.classList.add(`sort-${newOrder}`);
                header.dataset.order = newOrder;
                
                // 触发排序事件
                if (options.onSort) {
                    options.onSort(sortField, newOrder);
                }
            });
        });
        
        // 添加全选功能
        const selectAllCheckbox = table.querySelector('thead input[type="checkbox"]');
        const rowCheckboxes = table.querySelectorAll('tbody input[type="checkbox"]');
        
        if (selectAllCheckbox && rowCheckboxes.length > 0) {
            selectAllCheckbox.addEventListener('change', () => {
                rowCheckboxes.forEach(checkbox => {
                    checkbox.checked = selectAllCheckbox.checked;
                });
                
                if (options.onSelectionChange) {
                    options.onSelectionChange(this.getSelectedIds(tableId));
                }
            });
            
            rowCheckboxes.forEach(checkbox => {
                checkbox.addEventListener('change', () => {
                    const checkedCount = Array.from(rowCheckboxes).filter(cb => cb.checked).length;
                    selectAllCheckbox.checked = checkedCount === rowCheckboxes.length;
                    selectAllCheckbox.indeterminate = checkedCount > 0 && checkedCount < rowCheckboxes.length;
                    
                    if (options.onSelectionChange) {
                        options.onSelectionChange(this.getSelectedIds(tableId));
                    }
                });
            });
        }
    }
    
    // 获取选中的ID列表
    static getSelectedIds(tableId) {
        const table = document.getElementById(tableId);
        if (!table) return [];
        
        const checkedBoxes = table.querySelectorAll('tbody input[type="checkbox"]:checked');
        return Array.from(checkedBoxes).map(checkbox => checkbox.value);
    }
    
    // 清空表格选择
    static clearTableSelection(tableId) {
        const table = document.getElementById(tableId);
        if (!table) return;
        
        const checkboxes = table.querySelectorAll('input[type="checkbox"]');
        checkboxes.forEach(checkbox => {
            checkbox.checked = false;
            checkbox.indeterminate = false;
        });
    }
    
    // 格式化状态徽章
    static formatStatusBadge(status, type = 'user') {
        const statusConfig = {
            user: {
                1: { class: 'status-active', text: '正常' },
                0: { class: 'status-inactive', text: '禁用' }
            },
            product: {
                1: { class: 'status-active', text: '上架' },
                0: { class: 'status-inactive', text: '下架' }
            },
            review: {
                0: { class: 'status-pending', text: '待审核' },
                1: { class: 'status-approved', text: '已通过' },
                2: { class: 'status-rejected', text: '已拒绝' }
            }
        };
        
        const config = statusConfig[type] && statusConfig[type][status];
        if (!config) return `<span class="badge bg-secondary">${status}</span>`;
        
        return `<span class="badge \${config.class}">\${config.text}</span>`;
    }
    
    // 格式化操作按钮
    static formatActionButtons(id, type, status = null) {
        let buttons = '';
        
        switch (type) {
            case 'user':
                buttons = `
                    <button class="btn btn-sm btn-info" onclick="AdminUtils.viewUser(\${id})" title="查看">
                        <i class="fas fa-eye"></i>
                    </button>
                    <button class="btn btn-sm btn-warning" onclick="AdminUtils.editUser(\${id})" title="编辑">
                        <i class="fas fa-edit"></i>
                    </button>
                    <button class="btn btn-sm ${status == 1 ? 'btn-secondary' : 'btn-success'}" 
                            onclick="AdminUtils.toggleUserStatus(\${id})" title="\${status == 1 ? '禁用' : '启用'}">
                        <i class="fas ${status == 1 ? 'fa-ban' : 'fa-check'}"></i>
                    </button>
                    <button class="btn btn-sm btn-primary" onclick="AdminUtils.resetPassword(\${id})" title="重置密码">
                        <i class="fas fa-key"></i>
                    </button>
                    <button class="btn btn-sm btn-danger" onclick="AdminUtils.deleteUser(\${id})" title="删除">
                        <i class="fas fa-trash"></i>
                    </button>
                `;
                break;
                
            case 'product':
                buttons = `
                    <button class="btn btn-sm btn-info" onclick="AdminUtils.viewProduct(\${id})" title="查看">
                        <i class="fas fa-eye"></i>
                    </button>
                    <button class="btn btn-sm btn-warning" onclick="AdminUtils.editProduct(\${id})" title="编辑">
                        <i class="fas fa-edit"></i>
                    </button>
                    <button class="btn btn-sm ${status == 1 ? 'btn-secondary' : 'btn-success'}" 
                            onclick="AdminUtils.toggleProductStatus(\${id})" title="\${status == 1 ? '下架' : '上架'}">
                        <i class="fas ${status == 1 ? 'fa-eye-slash' : 'fa-eye'}"></i>
                    </button>
                    <button class="btn btn-sm btn-danger" onclick="AdminUtils.deleteProduct(\${id})" title="删除">
                        <i class="fas fa-trash"></i>
                    </button>
                `;
                break;
                
            case 'review':
                if (status == 0) { // 待审核
                    buttons = `
                        <button class="btn btn-sm btn-info" onclick="AdminUtils.viewReview(\${id})" title="查看">
                            <i class="fas fa-eye"></i>
                        </button>
                        <button class="btn btn-sm btn-success" onclick="AdminUtils.auditReview(\${id}, 1)" title="通过">
                            <i class="fas fa-check"></i>
                        </button>
                        <button class="btn btn-sm btn-warning" onclick="AdminUtils.auditReview(\${id}, 2)" title="拒绝">
                            <i class="fas fa-times"></i>
                        </button>
                        <button class="btn btn-sm btn-danger" onclick="AdminUtils.deleteReview(\${id})" title="删除">
                            <i class="fas fa-trash"></i>
                        </button>
                    `;
                } else {
                    buttons = `
                        <button class="btn btn-sm btn-info" onclick="AdminUtils.viewReview(\${id})" title="查看">
                            <i class="fas fa-eye"></i>
                        </button>
                        <button class="btn btn-sm btn-danger" onclick="AdminUtils.deleteReview(\${id})" title="删除">
                            <i class="fas fa-trash"></i>
                        </button>
                    `;
                }
                break;
        }
        
        return `<div class="action-buttons">${buttons}</div>`;
    }
    
    // 确认对话框
    static async confirm(message, title = '确认操作') {
        return new Promise((resolve) => {
            const modal = document.createElement('div');
            modal.className = 'modal fade';
            modal.innerHTML = `
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">${title}</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                        </div>
                        <div class="modal-body">
                            <p>${message}</p>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                            <button type="button" class="btn btn-danger" id="confirm-btn">确认</button>
                        </div>
                    </div>
                </div>
            `;
            
            document.body.appendChild(modal);
            
            const bsModal = new bootstrap.Modal(modal);
            bsModal.show();
            
            modal.querySelector('#confirm-btn').addEventListener('click', () => {
                bsModal.hide();
                resolve(true);
            });
            
            modal.addEventListener('hidden.bs.modal', () => {
                document.body.removeChild(modal);
                resolve(false);
            });
        });
    }
    
    // 显示加载状态
    static showLoading(containerId) {
        const container = document.getElementById(containerId);
        if (container) {
            container.innerHTML = `
                <div class="admin-loading">
                    <div class="loading"></div>
                    <p>加载中...</p>
                </div>
            `;
        }
    }
    
    // 显示空状态
    static showEmpty(containerId, message = '暂无数据', icon = 'fa-inbox') {
        const container = document.getElementById(containerId);
        if (container) {
            container.innerHTML = `
                <div class="empty-state">
                    <i class="fas ${icon}"></i>
                    <h4>暂无数据</h4>
                    <p>${message}</p>
                </div>
            `;
        }
    }
    
    // 刷新页面数据
    static refreshPage() {
        window.location.reload();
    }
    
    // 导出数据
    static exportData(data, filename, type = 'csv') {
        let content = '';
        let mimeType = '';
        
        if (type === 'csv') {
            // 转换为CSV格式
            if (data.length > 0) {
                const headers = Object.keys(data[0]).join(',');
                const rows = data.map(row => Object.values(row).join(',')).join('\n');
                content = headers + '\n' + rows;
            }
            mimeType = 'text/csv;charset=utf-8;';
        } else if (type === 'json') {
            content = JSON.stringify(data, null, 2);
            mimeType = 'application/json;charset=utf-8;';
        }
        
        const blob = new Blob([content], { type: mimeType });
        const url = URL.createObjectURL(blob);
        Utils.downloadFile(url, filename);
        URL.revokeObjectURL(url);
    }
    
    // 格式化文件大小
    static formatFileSize(bytes) {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }
    
    // 初始化图表
    static initChart(canvasId, config) {
        const canvas = document.getElementById(canvasId);
        if (!canvas) return null;
        
        // 销毁已存在的图表
        if (window.charts && window.charts[canvasId]) {
            window.charts[canvasId].destroy();
        }
        
        // 创建新图表
        const chart = new Chart(canvas, config);
        
        // 保存图表实例
        if (!window.charts) window.charts = {};
        window.charts[canvasId] = chart;
        
        return chart;
    }
    
    // 更新图表数据
    static updateChart(canvasId, newData) {
        if (window.charts && window.charts[canvasId]) {
            const chart = window.charts[canvasId];
            chart.data = newData;
            chart.update();
        }
    }
}

// 管理员权限检查
class AdminAuth {
    static async checkPermission() {
        try {
            const hasPermission = await AdminApiClient.checkAdminPermission();
            if (!hasPermission) {
                MessageUtil.showError('您没有管理员权限');
                setTimeout(() => {
                    window.location.href = '/product-review/login';
                }, 2000);
                return false;
            }
            return true;
        } catch (error) {
            console.error('权限检查失败:', error);
            MessageUtil.showError('权限验证失败，请重新登录');
            setTimeout(() => {
                window.location.href = '/product-review/login';
            }, 2000);
            return false;
        }
    }
    
    static async logout() {
        try {
            await ApiClient.post('/api/auth/logout');
            MessageUtil.showSuccess('退出成功');
            setTimeout(() => {
                window.location.href = '/product-review/login';
            }, 1000);
        } catch (error) {
            console.error('退出失败:', error);
            MessageUtil.showError('退出失败');
        }
    }
}

// 页面初始化
document.addEventListener('DOMContentLoaded', () => {
    // 初始化侧边栏
    AdminUtils.initSidebar();
    
    // 检查管理员权限
    AdminAuth.checkPermission();
    
    // 初始化工具提示
    const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });
});

// 导出到全局
window.AdminApiClient = AdminApiClient;
window.AdminUtils = AdminUtils;
window.AdminAuth = AdminAuth;